package com.googlecode.gwtbb.client.only.widget.display.picture;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;
import com.googlecode.gwtbb.client.shared.entity.picture.ImageProperties;
import com.googlecode.gwtbb.client.shared.util.PictureUtils;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Aug 6, 2008
 */
public class PropImage extends Composite {
	private Image image;
	private boolean scaled;
	private int scaledWidth;
	private int scaledHeight;

	public PropImage(ImageProperties imageProperties) {
		this(imageProperties, imageProperties.getWidth(), imageProperties.getHeight());
	}

	public PropImage(ImageProperties imageProperties, int maxWidth, int maxHeight) {
		int imgWidth = imageProperties.getWidth();
		int imgHeight = imageProperties.getHeight();
		if (imgWidth > maxWidth || imgHeight > maxHeight) {
			double imgAspectRatio = PictureUtils.getAspectRatio(imgWidth, imgHeight);
			double maxAspectRatio = PictureUtils.getAspectRatio(maxWidth, maxHeight);

			if (imgAspectRatio > maxAspectRatio) {
				imgWidth = maxWidth;
				imgHeight = (int)Math.round(maxWidth / imgAspectRatio);
			} else if (imgAspectRatio < maxAspectRatio) {
				imgWidth = (int)Math.round(maxHeight * imgAspectRatio);
				imgHeight = maxHeight;
			} else {
				imgWidth = maxWidth;
				imgHeight = maxHeight;
			}
			scaledWidth = imgWidth;
			scaledHeight = imgHeight;
			scaled = true;
		}
		image = new Image(imageProperties.getUrl());
		image.setPixelSize(imgWidth, imgHeight);
		initWidget(image);
	}

	public Image getImage() {
		return image;
	}

	public int getScaledHeight() {
		return scaledHeight;
	}

	public int getScaledWidth() {
		return scaledWidth;
	}

	public boolean isScaled() {
		return scaled;
	}
}
